Java - How to declare table[i][j] elements as instance variables?

Posted by JDelage on Stack Overflow See other posts from Stack Overflow or by JDelage
Published on 2010-03-28T16:46:31Z Indexed on 2010/03/28 16:53 UTC
Read the original article Hit count: 281

Filed under:
|
|

All,

I am trying to code a Connect4 game. For this, I have created a P4Game class and a P4Board class which represents the i X j dimensions of the Connect4 board.

In P4Game, I have the following:

public class P4Game{
  //INSTANCE VARIABLES
  private int nbLines;
  private int nbColumns;
  private P4Board [][] position;  

//CONSTRUCTOR  
  public P4Game(int nbLines, int nbColumns){
    this.nbColumns = nbColumns;
    this.nbLines = nbLines;
    P4Board [][] position = new P4Board [nbLines][nbColumns]; //Creates the table to receive the instances of the P4Board object.*/
    for (int i=0; i<nbLines; i++){
      for (int j=0; j<nbColumns; j++){
        this.position[i][j] = new P4Board(i,j); //Meant to create each object at (line=i, column=j)
      }
    } 
  }

This causes a NullPointerException in the nested loops where I mention this.position[i][j]. I reference those objects in other methods of this class so I need them to be instance variables. I suppose the exception is due to the fact that I have not listed the table element position[i][j] as an instance variable at the beginning of the class.

my question to people here is (1) is my assumption correct, and if so (2) what would be the syntax to declare instance variables of this form?

Thank you all for your help with what I realize is a very basic question. Hopefully it will also benefit other newbies.

Cheers,

JDelage

© Stack Overflow or respective owner

Related posts about java

Related posts about beginner